<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 点赞/取消点赞
 *
 * @author      Eden
 * @datetime    2016/12/9 00:43
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
class Likes_Model extends API_Model
{

    private $likes = 0;

    /**
     * 参数
     * @var array
     */
    private $params = array();

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主函数
     * @param array $params
     */
    public function run(Array $params)
    {
        $this->params = $params;
        $send['state'] = false;
        do {

            if (!$this->_checkParams()) {
                $send['error'] = $this->getError();
                break;
            }

            $db = clone($this->db);
            $query = $db->get_where('bbs', array('id' => $this->params['bbsId']));
            $row = $query->row_array();
            if (empty($row) || empty($row['id'])) {
                $send['error'] = '帖子不存在';
                break;
            }

            $type = $params['action'] == 'digg' ? '点赞' : '取消';
            if (!$this->thumbUp($params, $row)) {
                $error = $this->getError();
                $send['error'] = !empty($error) ? $error : $type . '失败';
            } else {
                $send['state'] = true;
                $send['data'] = [
                    'likes' => $this->likes,
                    'msg' => $type . '成功'
                ];
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 是否点赞
     * @param array $params
     * @return bool
     */
    private function thumbUp(Array $params, Array $bbsInfo)
    {
        $db = clone($this->db);
        $q = $db->get_where('bbs_likes', array('userId' => $params['userId'], 'bbsId' => $params['bbsId']));
        $row = $q->row_array();
        if ($params['action'] == 'digg') {
            if (!empty($row)){
                $this->setError('用户已点赞');
                return false;
            }

            $db->trans_start();
            $db->insert('bbs_likes', [
                'userId' => $params['userId'],
                'bbsId' => $params['bbsId'],
                'created' => dateTime()
            ]);

            $this->likes = $likes = intval($bbsInfo['likes']) + 1;
            $db->where('id', $params['bbsId']);
            $db->update('bbs', [
                'likes' => $likes
            ]);

            $db->trans_complete();
            return $db->trans_status();
        } else {
            // 取消
            if (empty($row)) {
                $this->setError('用户未点赞');
                return false;
            }

            $db->trans_start();
            $db->where(['userId' => $params['userId'], 'bbsId' => $params['bbsId']]);
            $db->delete('bbs_likes');

            $likes = intval($bbsInfo['likes']) - 1;
            $this->likes = $likes = $likes <= 0 ? 0 : $likes;
            $this->db->where('id', $params['bbsId']);
            $this->db->update('bbs', ['likes' => $likes]);
            $db->trans_complete();

            return $db->trans_status();
        }
    }

    /**
     * 检查参数
     * @return bool
     */
    private function _checkParams()
    {
        if (empty($this->params['userId'])) {
            $this->setError('用户未登录');
            return false;
        }

        if (empty($this->params['action']) || empty($this->params['bbsId'])) {
            $this->setError('缺少必填参数');
            return false;
        }

        if (!in_array($this->params['action'], array('digg', 'cancel'))) {
            $this->setError('不支持的操作类型');
            return false;
        }

        return true;
    }
}